<?php

class CustomFieldController extends PsController
{

	public $layout = 'manage';

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('ManageAgency.CustomField.Manage'),
					),
						), parent::accessRules());
	}

	public function actionIndex($model = 'Contact')
	{
		$customFieldModels = CustomFieldModel::getCustomFieldModels();
		if (!in_array($model, $customFieldModels)) {
			throw new CHttpException(400, 'Invalid request');
		}

		$criteria = new CDbCriteria;
		$criteria->compare('t.agency_id', Yii::app()->user->model->agency_id);

		$page = new CPagination;
		$page->pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 50;

		$sort = new CSort;
		$sort->defaultOrder = 't.pos ASC';

		$dataProvider = new CActiveDataProvider('CustomField', array(
					'criteria' => $criteria,
					'sort' => $sort,
					'pagination' => $page
				));

		if ($model != '') {
			$criteria = $dataProvider->getCriteria();
			$criteria->compare('t.custom_field_model', $model);
			$dataProvider->setCriteria($criteria);
		}

		$data = array();
		$data['customFieldModel'] = $model;
		$data['dataProvider'] = $dataProvider;

		$this->render('index', $data);
	}

	public function actionCreate($model)
	{
		$customFieldModels = CustomFieldModel::getCustomFieldModels();
		if (!in_array($model, $customFieldModels)) {
			throw new CHttpException(400, 'Invalid request');
		}

		$customField = new CustomField;
		$agencyId = Yii::app()->user->model->agency_id;

		if (isset($_POST['CustomField'])) {
			$customField->attributes = $_POST["CustomField"];
			$customField->agency_id = $agencyId;
			$customField->custom_field_model = $model;
			$isValid = $customField->validate();

			if ($isValid) {
				$transaction = Yii::app()->db->beginTransaction();

				try {
					$customField->save(false);

					// create or update custom field table
					$transaction->commit();
					PsSystemMessage::add('Custom field added.', 'success');
				} catch (CDbException $e) {
					$transaction->rollback();
					PsSystemMessage::add('Error adding custom field.', 'error');
				}
				$this->redirect(array('customField/index', 'model' => $model));
			} else {
//				dump($customField->getErrors());
			}
		}
		$data = array();
		$data['customField'] = $customField;
		$data['customFieldModel'] = $model;
		$data['customFieldGroups'] = $this->getCustomFieldGroupsListData($model);
		$this->render('create', $data);
	}

	public function actionUpdate($id)
	{
		$customField = $this->loadModel($id);
		$type = $customField->custom_field_type;

		if (isset($_POST['CustomField'])) {
			$transaction = Yii::app()->db->beginTransaction();

			try {
				$customField->attributes = $_POST["CustomField"];
				$customField->agency_id = Yii::app()->user->model->agency_id;

				$isValid = $customField->validate();
				if ($isValid) {
					$customField->save();
				}
				$transaction->commit();
				PsSystemMessage::add('Custom field updated.', 'success');
			} catch (CDbException $e) {
				$transaction->rollback();
				PsSystemMessage::add('Custom field not updated.', 'failure');
			}
			$this->redirect(array('customField/index', 'type' => $type));
		}
		$data = array();
		$data['customFieldGroups'] = $this->getCustomFieldGroupsListData($customField->custom_field_model);
		$data['customField'] = $customField;
		$data['type'] = $type;
		$this->render('update', $data);
	}

	public function actionDelete($id)
	{
		$response = array();

		$customField = $this->loadModel($id);
		if ($customField->delete()) {
			$response["result"] = "success";
			$response["successMsg"] = "Custom field deleted.";
		} else {
			$response["result"] = "failure";
			$response["errorMsg"] = "Error deleting custom field.";
		}
		print CJSON::encode($response);
	}

	public function loadModel($id)
	{
		$model = CustomField::model()->ofCurrentAgency()->findByPk($id);

		if ($model == null) {
			throw new PsPageNotFoundException();
		}

		return $model;
	}

	public function getCustomFieldGroupsListData($model) {
		$customFieldGroups = CustomFieldGroup::model()->ofCurrentAgency()->findAllByAttributes(array(
			'custom_field_model' => $model
		));
		
		return CHtml::listData($customFieldGroups, 'id', 'name');
	}
}
